package com.ctsi.ssdc.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {

    public static Date date(String year, String month) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date date = null;
        try {
            date = simpleDateFormat.parse(year + "-" + month);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 转化为字符串形式  yyyy-MM
     * @param date
     * @return 格式化的字符串
     */
    public static String toString(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        return format.format(date);
    }

    /**
     * 从当前时间向后偏移n年
     * @param year 过期年份
     * @return ZonedDateTime
     */
    public static ZonedDateTime getZoneExpiredTime(int year) {
        Date date = new Date();
        date = addYear(date, year);
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = date.toInstant();
        return ZonedDateTime.ofInstant(instant, zoneId);
    }

    public static Date addYear(Date date, int year) {
        return date(year(date) + year, month(date));
    }

    public static Date addMonth(Date date, int month) {
        int mon = month(date) + month;
        if (mon > 12) {
            int year = mon / 12;
            month = mon % 12;
            date = addYear(date, year);
        } else if (mon < 1) {
            mon--;
            int year = mon / 12;
            month = mon % 12;
            date = addYear(date, year);
        }
        return date(year(date), month(date) + month);
    }

    public static Date date(int year, int month) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date date = null;
        try {
            date = simpleDateFormat.parse(year + "-" + month);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;

    }

    public static int year(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    public static int month(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }
}
